/*
 * このソースコードはKeiji Ariyamaさんのご厚意で提供いただきました。ありがとー。
 */

package android.hackathon.bp.hayaben;

import java.util.BitSet;

import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.util.Log;

public class WiFiUtils {
	private static boolean DEBUG_FLG = true;
	private static String LOG_TAG = "WiFiUtils";

    /**
     * 
     * @param data
     * @return
     */
    public static final int bitset2Int(BitSet data) {

    	int result = 0;
    	int val = 1;

    	int len = data.size();
    	for(int i=1; i < len; i++) {
    		if(data.get(i)) result += val;
    		val <<= 1;
    	}

    	return result;
    }

    /**
     * WiFi設定の生成
     * @param uri
     * @return
     */
    public static final String generateWiFiSetting(WifiConfiguration conf) {
    	StringBuffer sb = new StringBuffer();

    	String s = "&";

    	sb.append("wifi://setting?");

    	sb.append("ssid=");
    	sb.append(conf.SSID.replace("\"", ""));
    	sb.append(s);

    	String[] wepKeys = conf.wepKeys;
    	if(wepKeys != null && wepKeys.length > 0) {
    		if(wepKeys[0] != null && wepKeys[0].equals("")) {
            	sb.append("wep=");
            	sb.append(wepKeys[0].replace("\"", ""));
            	sb.append(s);
    		}
    	}

    	sb.append("keyman=");
    	sb.append(bitset2Int(conf.allowedKeyManagement));
    	sb.append(s);


    	sb.append("gcipher=");
    	sb.append(bitset2Int(conf.allowedGroupCiphers));
    	sb.append(s);


    	sb.append("authalgo=");
    	sb.append(bitset2Int(conf.allowedAuthAlgorithms));


    	if(conf.BSSID != null) {
        	sb.append(s);
        	sb.append("bssid=");
        	sb.append(conf.BSSID.replace("\"", ""));
    	}

    	sb.append(s);
    	sb.append("hssid=");
    	if(conf.hiddenSSID) {
        	sb.append("t");
    	} else {
        	sb.append("f");
    	}

    	if(conf.preSharedKey != null) {
        	sb.append(s);
        	sb.append("psk=");
        	sb.append(conf.preSharedKey.replace("\"", ""));
    	}

    	if(DEBUG_FLG) Log.d(LOG_TAG, "test " + sb.toString());
    	
    	return sb.toString();
//    	return URLEncoder.encode(sb.toString());
    }

    /**
     * WiFi設定の生成
     * @param uri
     * @return
     */
    public static final WifiConfiguration generateWiFiSetting(Uri uri) {
    	if(DEBUG_FLG) Log.e(LOG_TAG, "wifi uri = " + uri.toString());
    	final WifiConfiguration result = new WifiConfiguration();

    	String query = uri.getEncodedQuery();
    	String[] queries = query.split("&");

    	for(String seg : queries) {

    		String[] val = seg.split("=");

    		String key = val[0];
    		String value = val[1];
    		
    		if(key.equals("ssid")) {
    			result.SSID = "\"" +value+ "\"";

    		} else if(key.equals("wep")) {
    			result.wepKeys = new String[] {value, value, value, value};
    			result.wepTxKeyIndex = 0;
    		
    		} else if(key.equals("keyman")) {
    			result.allowedKeyManagement.set(Integer.parseInt(value));
    		
    		} else if(key.equals("gcipher")) {
    			result.allowedGroupCiphers.set(Integer.parseInt(value));

    		} else if(key.equals("authalgo")) {
    			result.allowedAuthAlgorithms.set(Integer.parseInt(value));

    		} else if(key.equals("bssid")) {
    			result.BSSID = "\"" +value+ "\"";

    		} else if(key.equals("hssid")) {

    			if(value.equals("t")) {
	    			result.hiddenSSID = true;
    			} else {
	    			result.hiddenSSID = false;
    			}
    		
    		} else if(key.equals("psk")) {
    			result.preSharedKey = "\"" +value+ "\"";
    		}

    	}
    	    	
    	result.priority = 1;
    	result.status=WifiConfiguration.Status.ENABLED;
    	
    	return result;
    }

    public static String getGroupCiphers(BitSet bs) {
    	StringBuffer sb = new StringBuffer();
    	int bit = WiFiUtils.bitset2Int(bs);
    	
    	boolean flg = false;

    	if((bit&WifiConfiguration.GroupCipher.CCMP) != 0) {
        	if(flg) sb.append("/");
    		sb.append("CCMP");
    		flg = true;
    	}
    	if((bit&WifiConfiguration.GroupCipher.TKIP) != 0) {
        	if(flg) sb.append("/");
    		sb.append("TKIP");
    		flg = true;
    	}
    	if((bit&WifiConfiguration.GroupCipher.WEP104) != 0) {
        	if(flg) sb.append("/");
    		sb.append("WEP104");
    		flg = true;
    	}
    	if((bit&WifiConfiguration.GroupCipher.WEP40) != 0) {
        	if(flg) sb.append("/");
    		sb.append("WEP40");
    		flg = true;
    	}

    	return sb.toString();
    }

    public static String getKeyManagement(BitSet bs) {
    	StringBuffer sb = new StringBuffer();
    	int bit = WiFiUtils.bitset2Int(bs);
    	
    	boolean flg = false;
    	if(bit == 0) return "NONE";
    	if((bit&WifiConfiguration.KeyMgmt.IEEE8021X) != 0) {
        	if(flg) sb.append("/");
    		sb.append("IEEE8021X");
    		flg = true;
    	}
    	if((bit&WifiConfiguration.KeyMgmt.WPA_EAP) != 0) {
        	if(flg) sb.append("/");
    		sb.append("WPA_EAP");
    		flg = true;
    	}
    	if((bit&WifiConfiguration.KeyMgmt.WPA_PSK) != 0) {
        	if(flg) sb.append("/");
    		sb.append("WPA_PSK");
    		flg = true;
    	}

    	return sb.toString();
    }

    public static String getState(int value) {
    	switch(value) {
    	case WifiConfiguration.Status.CURRENT:
    		return "current";
    	case WifiConfiguration.Status.DISABLED:
    		return "disabled";
    	case WifiConfiguration.Status.ENABLED:
    		return "enabled";
    	};
    	return "security";
    }

	public static final boolean hasWepKey(WifiConfiguration data) {
		if(data.wepKeys != null
				&& data.wepKeys[0] != null && data.wepKeys[0].equals("*")) {
			return true;
		} else {
			return false;
		}
	}

	public static final boolean hasPSK(WifiConfiguration data) {
		if(data.preSharedKey != null && data.preSharedKey.equals("*")) {
			return true;
		} else {
			return false;
		}
	}

}
